package com.yuanmeng.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.ObjectUtils;

import com.yuanmeng.common.core.enums.BooleanFlagEnum;

/**
 * 时间工具类
 *
 * @author 安然
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String    YYYY                = "yyyy";

    public static String    YYYY_MM             = "yyyy-MM";

    public static String    YYYY_MM_DD          = "yyyy-MM-dd";

    public static String    YYYYMMDDHHMMSS      = "yyyyMMddHHmmss";

    public static String    YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns       = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss",
                                                    "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd",
                                                    "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
                                                    "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
                                                    "yyyy.MM.dd HH:mm", "yyyy.MM" };

    public static String    RFC3339             = "yyyy-MM-dd'T'HH:mm:ssXXX";

    public static String    CURRENT_SUM         = "EEEE";

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差多少天
     */
    public static Long calculateIntervalNum(Date startDate, Date stopDate) {
        long nd = 1000 * 24 * 60 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = stopDate.getTime() - startDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        System.out.println(day);
        return day;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @description   获取*单位后的时间
     * @param num 时间单位数（如果num数为负数,说明是此日期前的天数）
     * @param Calendar.HOUR 时间类型：小时
     */
    public static Date generatorUnitTime(Date date, Long num) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, num.intValue());
        return cal.getTime();
    }

    /**
     * @description   获取*单位后的时间
     * @param num 时间单位数（如果num数为负数,说明是此日期前的天数）
     * @param field 时间类型: 天:Calendar.DAY_OF_YEAR
     */
    public static Date generatorUnitTime(Date date, Long num, int field) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, num.intValue());
        return cal.getTime();
    }

    /**
     * 获取两个时间段内的毫秒数
     * @param beginTime
     * @param endTime
     * @return
     */
    public static Long generatorMills(Date beginTime, Date endTime) {
        Calendar nowDate = Calendar.getInstance();
        Calendar oldDate = Calendar.getInstance();
        nowDate.setTime(endTime);
        oldDate.setTime(beginTime);
        Long timeNow = nowDate.getTimeInMillis();
        Long timeOld = oldDate.getTimeInMillis();
        Long time = (timeNow - timeOld);
        return time;
    }

    /**
     * 判断是否为当前时间的前一天
     * @param lastTime
     * @param nowDate
     * @return
     */
    public static Boolean dayBeforeCurrentTime(Date lastTime, Date nowDate) {
        String lastTimeStr = dateTime(lastTime);

        String nowDateStr = dateTime(generatorUnitTime(nowDate, -1L, Calendar.DAY_OF_YEAR));
        if (lastTimeStr.equals(nowDateStr)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为当天
     * @param lastTime
     * @param nowDate
     * @return
     */
    public static Boolean currentTimeSameDay(Date lastTime, Date nowDate) {
        String lastTimeStr = dateTime(lastTime);
        String nowDateStr = dateTime(nowDate);
        if (lastTimeStr.equals(nowDateStr)) {
            return true;
        }
        return false;
    }

    /**
     * 获取指定时间为星期几
     * @param date
     * @return
     */
    public static String currentSun(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(CURRENT_SUM);
        return dateFormat.format(getNowDate());
    }

    /**
     * 校验当前时间是否在两个时间点内（时分）
     * @param beginTime
     * @param endTime
     * @param currentTime
     * @return
     */
    public static String validateCurrentTime(String beginTime, String endTime, Date currentTime) {
        if (!ObjectUtils.isEmpty(beginTime) && ObjectUtils.isEmpty(endTime)) {
            String nowDate = parseDateToStr(YYYY_MM_DD, currentTime);
            String beginTimes = nowDate + " " + beginTime;
            String endTimes = nowDate + " " + endTime;

            System.out.println("beginTimes:" + beginTimes);
            System.out.println("endTimes:" + endTimes);

            Date startTime = dateTime(YYYY_MM_DD_HH_MM_SS, beginTimes);
            Date stopTime = dateTime(YYYY_MM_DD_HH_MM_SS, endTimes);

            if (currentTime.after(startTime) && currentTime.before(stopTime)) {
                return BooleanFlagEnum.TRUE.getCode();
            } else {
                return BooleanFlagEnum.FALSE.getCode();
            }
        }
        return BooleanFlagEnum.TRUE.getCode();
    }

    /**
     * 获取当前时间距离当天结束
     * @param type ChronoUnit.MILLIS 毫秒  ChronoUnit.SECONDS 秒
     * @return
     */
    public static Long timeLeftInTheDay(ChronoUnit type) {
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0)
            .withSecond(0).withNano(0);
        return type.between(LocalDateTime.now(), midnight);
    }

    /**
     * 获取当前时间-年/-月
     * @param dateType
     * @return
     */
    public static String currentDateInfo(int dateType) {
        Calendar calendar = Calendar.getInstance();

        if (Calendar.YEAR == dateType) {
            return String.valueOf(calendar.get(Calendar.YEAR));
        }

        if (Calendar.MONTH == dateType) {
            return String.valueOf(calendar.get(Calendar.MONTH) + 1);
        }
        return "";
    }

    /**
     * 获取当月第一天
     * @return
     */
    public static Date getNowMonthFirstDay() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_MONTH, 1);
        parseDate(dateTime(cal.getTime()));
        return parseDate(dateTime(cal.getTime()));
    }

    /**
     * 获取下月第一天
     * @return
     */
    public static Date getFirstDayOfNextMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        System.out.println(parseDate(dateTime(calendar.getTime())));
        return parseDate(dateTime(calendar.getTime()));
    }

    public static void main(String[] args) {
        System.out.println(generatorUnitTime(DateUtils.getNowDate(), 1L));
    }
}
